/*
 * Server.cpp
 *
 *  Created on: Jun 1, 2011
 *      Author: madboyka
 */

#include "Server.h"
#include <iostream>
#include <stdio.h>
#include "config.h"
#include "NetworkTest.h"
#include "ElementData.h"

//ElementData *NetworkTest::edata;

Server::Server(ViewerProtocol* p)
{
	protocol = p;
	stage = 0;
	errorCount = 0;
}

Server::~Server()
{
	protocol->close();
	delete protocol;
}
void Server::run()
{
	try
	{
		protocol->bind();
		puts("S Waiting for connection...");
		ViewerProtocol* bla = protocol->acceptConnection();
		if (stage == 0)
		{
			puts("S Waiting for request...");
			bla->waitRequest();
			puts("S Serving response...");
			bla->sendMessage(1, 0);
		}
		if (stage == 1)
		{
			float mat[] =
			{ 1.500, 0.1321, 0.321321, 0.4433234324, 123320.32132, 1.323323,
					0.6000000, 0.212332121, 0, 0, 1, 0, 1, 1, 1, 1 };
			for (int i = 0; i < DATA_COUNT; ++i)
			{
				bla->waitRequest();
				printf("S Serving request number: %d\n", i);
				bla->sendMessage(3, 1);
				bla->sendObjects(mat, sizeof(float) * 16);
			}
		}
		if (stage == 2)
		{
			for (int i = 0; i < DATA_COUNT; ++i)
			{
				bla->waitRequest();
				printf("S Serving request number: %d\n", i);
				bla->sendMessage(1, 1);
				bla->writeElementData(*NetworkTest::edata);
			}
		}
		puts("Done...\n");
	} catch (NetworkException ex)
	{
		errorCount++;
		std::cout << ex.showReason().toStdString();
	}
}
